import tornado
import json
import tornado.websocket
import tornado.web
import time
from util.myredis import r
from db.datab import db
conndict={}
class WebsockHandler(tornado.websocket.WebSocketHandler):
    # 跨域支持
    def check_origin(self, origin):
        return True
    #建立连接
    def open(self):
        #获取参数
        id = int(self.get_query_argument("id"))
        #存储链接
        conndict[id]=self
    #接收消息
    def on_message(self,mes):
        print(mes)

    def on_close(self):
        pass


class TTHandler(tornado.web.RequestHandler):
    def get(self):
        msg = self.get_query_argument("mes")
        id = int(self.get_query_argument("id"))
        conndict[id].write_message(msg)




class Greenhouse(tornado.web.RequestHandler):
    def get(self):
        id = int(self.get_query_argument('id'))
        while True:

            web = r.str_get('key')
            print(web)
            if web:
                key = int(web.decode())
                sql = "select * from greenhouse"
                res = db.findAll(sql)
                print(res)
                list = []
                for i in res:
                    if i['min'] <= key <= i['max']:
                        status = 1
                        list.append({'id':i['id'],'name':i['name'],'min':i['min'],'max':i['max'],'status':status,'key':key})
                    else:
                        status = 0
                        list.append({'id':i['id'],'name':i['name'],'min':i['min'],'max':i['max'],'status':status,'key':key})
                time.sleep(3)
                conndict[id].write_message(json.dumps(list))

















